<!DOCTYPE html>
<meta charset="utf-8">
<script src="/bower_components/webcomponentsjs/webcomponents-loader.js"></script>
<script src="/bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="/bower_components/iron-test-helpers/iron-test-helpers.html">
<link rel="import" href="/elements/som-drawer/som-drawer.html">
<test-fixture id="basic">
  <template>
    <som-drawer></som-drawer>
  </template>
</test-fixture>
<script>
(function() {
  'use strict';

  suite('basic tests', function() {
    var element;
    var server;
    var stubbedFetch;
    var responseHeaders = {
        json: {'Content-Type': 'application/json'},
        text: {'Content-Type': 'text/html'},
    };

    setup(function() {
      element = fixture('basic');
      server = sinon.fakeServer.create();
      stubbedFetch = sinon.stub(window, 'fetch');

      element.$.fetchTrooper.auto = false;

      element.trees = {
        'name': 'chromium',
        'display_name': 'Chromium',
      };
    });

    teardown(function() {
      server.restore();
      stubbedFetch.restore();
    });

    test('renders current trooper', function(done) {
      element._trooperString = 'faketrooper';
      flush(function () {
        assert.equal('faketrooper (primary)',
          element.$.currentTroopers.textContent.trim());
        done();
      });
    });

    test('renders primary/secondary troopers', function(done) {
      element._trooperString = 'faketrooper,troopertoo';
      flush(function () {
        let troopers = element.$.currentTroopers.querySelectorAll('li');
        assert.equal(2, troopers.length);
        assert.equal('faketrooper (primary)', troopers[0].textContent.trim());
        assert.equal('troopertoo (secondary)', troopers[1].textContent.trim());
        done();
      });
    });

    test('gets current trooper', function(done) {
      server.respondWith(
        'GET',
        'https://rota-ng.appspot.com/legacy/current_trooper.txt', [
          200,
          responseHeaders.text,
          'helloworld'
        ]
      );

      element._refresh();

      server.respond();

      flush(function () {
        assert.equal('helloworld', element._trooperString);
        assert.deepEqual(['helloworld (primary)'], element._troopers);
        done();
      });
    });

    test('computes sheriffs from JSON', function(done) {
      const body = {emails: ['foo@example.com', 'bar@example.com']};
      const init = {status: 200, headers: responseHeaders.json};
      const response = new window.Response(JSON.stringify(body), init);
      stubbedFetch.returns(Promise.resolve(response));

      element.tree = {'name': 'chromium'};

      flush(function () {
        assert.equal(1, element._rotations.length);
        assert.deepEqual({
          name: 'Chromium Sheriff',
          people: ['foo@example.com', 'bar@example.com'],
        }, element._rotations[0]);
        done();
      });
    });
  });
})();
</script>
